package com.cwf.auth.interceptor;

import com.cwf.auth.data.ContextMap;
import com.cwf.basic.annotation.AutoScanPermission;
import com.cwf.org.domain.Employee;
import com.cwf.org.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("=========拦截器==========");
        // 获取前端请求的token
        String token = request.getHeader("token");
        System.out.println(token);
        if (Objects.isNull(token)){
            response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }
        // 根据token获取map中的对象
        Employee employee = ContextMap.loginMap.get(token);
        if (Objects.isNull(employee)){
            response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }

        // 鉴权
        // 1.判断访问资源是否需权限 - 判断请求方法是否有权限注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        AutoScanPermission annotation = handlerMethod.getMethodAnnotation(AutoScanPermission.class);
        if (Objects.nonNull(annotation)){
            // 2.如果需要权限
            // 3.获取用户资源
            List<String> sns = employeeMapper.querySNById(employee.getId());
            // 4.获取资源权限
            // 获取类型的两种方式：方式一
//            String simpleName = handlerMethod.getBean().getClass().getSimpleName();
            // 方式二：
            String simpleName = method.getDeclaringClass().getSimpleName();
            String methodName = method.getName();
            String permission = simpleName + ":" + methodName;
            // 5.判断用户权限是否包含资源权限
            if (!sns.contains(permission)){
                response.getWriter().println("{\"success\":false,\"msg\":\"noPermission\"}");
                return false;
            }
        }

        return true;
    }
}